<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/8/1
 * Time: 下午1:42
 */

namespace Hrm\Controllers;
use Helpers\Cache;
use Helpers\User;
use Helpers\UserPower;
use Admin\Models\hrm\XhhrmDepart;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Template;


class DepartmentController extends ControllerBase
{




    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['code' => 404, 'error' => 'page not found!']);
    }

    /**
     * 创建
     * @param $detail
     * @param $msg
     * @return bool
     * created by dale 2017/8/17
     */
    public function praseLog($detail,$msg){
        return Main::createCommitLog(
            'hrm',
            $this->dispatcher->getControllerName(),
            $this->dispatcher->getActionName(),
            ['post'=>$this->request->getPost(),'get'=>$this->request->getQuery(),'detail'=>$detail],
            null,
            $msg
        );
    }


    /**
     * 部门列表
     * created by dale 2017/8/16
     */
    public function depListAction(){
        UserPower::checkUserPower('Hrm_Dep') or die('权限不足');
        $this->di->get('assets')
            ->addCss('assets/sweetalert2/sweetalert2.min.css')
            ->addJs('assets/sweetalert2/sweetalert2.min.js');
        Assets::easyUI();
        Main::showNavPosition();
        Assets::importJs('js/myMain.js');
        $this->view->pick('department/depList');
        Assets::importJs('js/department/depList.js');
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importMainJs('assets/xh/xhTop.js');
        $this->view->setVars([
            'depEdit'=>UserPower::checkUserPower('Hrm_Dep_Edit'),
            'depAdd'=>UserPower::checkUserPower('Hrm_Dep_Add'),
            'depDel'=>UserPower::checkUserPower('Hrm_Dep_Del')
        ]);
    }


    public function depFormAction(){
        $iDepId=$this->request->getQuery('iDepId','string');
        if($iDepId){
            UserPower::checkUserPower('Hrm_Dep_Edit') or die('权限不足');
        }else{
            UserPower::checkUserPower('Hrm_Dep_Add') or die('权限不足');
        }

        Assets::easyUI();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/myMain.js');
        Assets::importJs('js/department/depForm.js');
        $this->view->pick('department/depForm');
    }


    /**
     * 获取部门信息
     * @return string
     *
     */
    public function getDepAction(){
        UserPower::checkUserPower('Hrm_Dep') or die('权限不足');
        $id=$this->request->getPost('id','string');
        if($id){
            return json_encode($this->recursionForArray($id));
        }
        return json_encode($this->recursionForArray(0));
    }

    /**
     * 获取部门信息  id ,text easyui
     * @return string
     * created by dale 2017/8/16
     */
    public function getDepEnumAction(){
        $newArray[0]['id']=0;
        $newArray[0]['text']='学海教育科技有限公司';
        $newArray[0]['iconCls']='fa fa-group';
        $newArray[0]['children']=$this->recursionForArray2(0);
        return json_encode($newArray);
    }

    /**
     * 删除部门
     * @return string
     * created by dale 2017/8/16
     */
    public function delDepAction(){
        UserPower::checkUserPower('Hrm_Dep_Del') or die('权限不足');
        $iDepId = $this->request->getPost('id','string');
        $obj    = XhhrmDepart::findFirst($iDepId);
        $obj->bDelete = 1;
        $result=$obj->save();
        if($result&&$this->recursionForDelete(array($iDepId))){
            $this->praseLog('循环删除部门成功','循环删除部门成功');
            if(Cache::exists('DepEnum')){
                Cache::delete('DepEnum');
            }
            return $this->sendSuccessResponse('删除成功');
        }else{
            $this->praseLog('循环删除部门失败','循环删除部门失败');
            return $this->sendSuccessResponse('删除失败');
        }
    }

    /**
     * 级联删除
     * @param $array
     * @return bool
     * created by dale 2017/8/16
     */
    public function recursionForDelete($array){

        $objs = XhhrmDepart::find([
            'conditions' => 'iParentId in ({ids:array}) AND bDelete=:bDelete: ',
            'bind' => ['ids' => $array,'bDelete' => 0]
        ]);
        $ids=[];
        if($objs==null){  //下面没有子部门
            return true;
        }
        foreach ($objs as $obj ){
            $obj->bDelete = 1;
            if(!$obj->save()){
                return false;
            }
            array_push($ids,$obj->iDepId);
        }
        if($ids==[]){
            return true;
        }else{
            return $this->recursionForDelete($ids);
        }
    }



    public function saveDepartmentAction(){
        $iDepId=$this->request->getPost('iDepId','string');
        if($iDepId){
            UserPower::checkUserPower('Hrm_Dep_Edit') or die('权限不足');
            $obj = XhhrmDepart::findFirst($iDepId);
        }else{
            UserPower::checkUserPower('Hrm_Dep_Add') or die('权限不足');
            $obj = new XhhrmDepart();
        }
        $obj->assign($this->request->getPost());
        if($iDepId){
            if(XhhrmDepart::findFirst([
                'conditions'=>'bDelete=0 AND sTag=:sTag: AND iDepId!= :iDepId:',
                'bind'=>['sTag'=>$this->request->getPost('sTag'),'iDepId'=>$iDepId]
            ])){
                return $this->sendErrorResponse(500,'错误,该标签存在');
            }
        }else{
            if(XhhrmDepart::findFirst([
//                'conditions'=>'bDelete=0 AND (sTag=:sTag: OR sDepName=:sDepName:)',
//                'bind'=>['sTag'=>$this->request->getPost('sTag'),'sDepName'=>$this->request->getPost('sDepName')]
                'conditions'=>'bDelete=0 AND sTag=:sTag: ',
                'bind'=>['sTag'=>$this->request->getPost('sTag')]
            ])){
                return $this->sendErrorResponse(500,'错误,该部门名称或者标签存在');
            }
        }
        $obj->sTag = ($this->request->getPost('sTag','string')==''?null:strtoupper(trim($this->request->getPost('sTag','string'))));
        $obj->iParentId = ($this->request->getPost('iParentId','string')==''?0:$this->request->getPost('iParentId','string'));
        $result = $obj->save();
        if($result){
            if(Cache::exists('DepEnum')){
                Cache::delete('DepEnum');
            }
            if($iDepId){

                return $this->sendSuccessResponse('编辑部门成功');
//                $this->praseLog('编辑部门成功','编辑部门成功');
            }else{

                return $this->sendSuccessResponse('保存部门成功');
//                $this->praseLog('保存部门成功','保存部门成功');
            }


        }else{
            if($iDepId){
                $this->sendSuccessResponse(500,'编辑部门失败');
                return false;
//                $this->praseLog('编辑部门失败','编辑部门失败');
            }else{
                $this->sendSuccessResponse(500,'保存部门失败');
                return false;
//                $this->praseLog('保存部门失败','保存部门失败');
            }
//            return 'fail';
        }
    }

    public function getDepInfoAction(){
        $iDepId=$this->request->getPost('id','string') or die('缺少参数');
        $obj = XhhrmDepart::findFirst($iDepId);
        $jsonArray=$obj->toArray();
        if($jsonArray['iParentId']==0){
            $jsonArray['inputPareName']='顶层';
        }else{
            $pObj = XhhrmDepart::findFirst($jsonArray['iParentId']);
            $jsonArray['inputPareName']=$pObj->sDepName;
        }
        return json_encode($jsonArray);
        
    }

    public function recursionForArray($parentId){
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: ",
            'bind' => array('parentId' =>$parentId , 'bDelete' => 0),
        );
        $objs=XhhrmDepart::find($parameters);
        if($objs==null){
            return [];
        }
        $array=$objs->toArray();
        Main::runUserName($array, ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId']);
        $newArray=[];
        foreach ($array as $key=>$value){
            $newArray[$key]=$value;
            $newArray[$key]['iconCls']='fa fa-group';
            $newArray[$key]['children']=$this->recursionForArray($value['iDepId']);
            if($newArray[$key]['children']){
                $newArray[$key]['state']="closed";
            }
        }

        return $newArray;
    }
    
    public function recursionForArray2($parentId){
        $parameters = array(
            'conditions' => "bDelete=:bDelete: AND iParentId=:parentId: ",
            'bind' => array('parentId' =>$parentId , 'bDelete' => 0),
        );
        $objs=XhhrmDepart::find($parameters);
        if($objs==null){
            return [];
        }
        $array=$objs->toArray();
        $newArray=[];
        foreach ($array as $key=>$value){
            $newArray[$key]['id']=$value['iDepId'];
            $newArray[$key]['text']=$value['sDepName'];
            $newArray[$key]['iconCls']='fa fa-group';
            $newArray[$key]['children']=$this->recursionForArray2($value['iDepId']);
            if($newArray[$key]['children']){
                $newArray[$key]['state']="closed";
            }
        }

        return $newArray;

    }

//    public function recursionForHtml($array,$showDelete=false){
//        $contentStr='';
//        foreach ($array as $key=>$value){
//            if($value==end($array)){
//                $contentStr.='<li class="openable last-link"><a nodeid="'.$value['iDepId'].'"><i class="fa fa-group m-right-xs "></i>'.$value['sDepName'].'</a>';
//            }else{
//                $contentStr.='<li class="openable"><a nodeid="'.$value['iDepId'].'"><i class="fa fa-group m-right-xs "></i>'.$value['sDepName'].'</a>';
//            }
//            if($showDelete){
//                $contentStr.='<i class="fa fa-times"></i>';
//            }
//            if($value['children']!=[]){
//                $contentStr.='<ul class="subtree">'.$this->recursionForHtml($value['children'],$showDelete).' </ul>';
//            }
//            $contentStr.='</li>';
//        }
//        return $contentStr;
//    }


//    public function getTreeHtml($showDelete=false){
//        $array = $this->recursionForArray(0);
//        $contentStr = $this->recursionForHtml($array,$showDelete);
//        return $contentStr;
//    }
    
    
    

    
    



    
    
}